use hypers::hyper::{Method, StatusCode};
use hypers::prelude::*;

pub async fn index(_: Request) -> Response {
    let res = Response::default();
    res.render(Text::Html(LOGIN_HTML))
}
pub async fn login(mut req: Request) -> Response {
    let mut res = Response::default();
    if req.method() == Method::POST {
        let mut session = Session::new();
        let _ = session.insert("username", req.form::<String>("username").await.unwrap());
        res.set_session(session);
        res.redirect(StatusCode::SEE_OTHER, "/");
        res
    } else {
        res.render(Text::Html(LOGIN_HTML))
    }
}

pub async fn logout(mut req: Request) -> Response {
    let mut res = Response::default();
    if let Some(session) = req.session_mut() {
        println!("session = {:?}", session);
        session.remove("username");
    }
    res.redirect(StatusCode::SEE_OTHER, "/");
    res
}

pub async fn home(mut req: Request) -> Response {
    let mut content = r#"<a href="login">Login</h1>"#.into();
    if let Some(session) = req.session_mut() {
        if let Some(username) = session.get::<String>("username") {
            content = format!(r#"Hello, {username}. <br><a href="logout">Logout</h1>"#);
        }
    }
    let res = Response::default();
    res.render(Text::Html(content))
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt().init();
    let mut root = Router::default();
    let session_hook = SessionHook::new(
        CookieStore::new(),
        b"secretabsecretabsecretabsecretabsecretabsecretabsecretabsecretab",
    )?;
    root.hook(session_hook, None, None);
    root.get("/", home)
        .get("/login", login)
        .post("/login", login) //http://127.0.0.1:7878/login
        .get("/logout", logout);
    println!("root = {:#?}", root);
    let listener = hypers::TcpListener::bind("127.0.0.1:7878").await?;
    hypers::listen(root, listener).await
}
static LOGIN_HTML: &str = r#"<!DOCTYPE html>
<html>
    <head>
        <title>Login</title>
    </head>
    <body>
        <form action="/login" method="post">
            <h1>Login</h1>
            <input type="text" name="username" />
            <button type="submit" id="submit">Submit</button>
        </form>
    </body>
</html>
"#;


